package com.bianxingji.service.impl;


import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bianxingji.constant.BxjType;
import com.bianxingji.constant.FileType;
import com.bianxingji.dto.BxjMovieDto;
import com.bianxingji.mapper.*;
import com.bianxingji.model.PageResult;
import com.bianxingji.po.*;
import com.bianxingji.service.BxjMovieService;
import com.bianxingji.utils.IdUtil;
import com.bianxingji.vo.BxjMovieBaseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wy
 */
@Slf4j
@Service
public class BxjMovieServiceImpl extends ServiceImpl<BxjMovieMapper, BxjMovie> implements BxjMovieService {
    
    @Autowired
    private BxjMovieMapper bxjMovieMapper;
    @Autowired
    private BxjMovieDetailMapper bxjMovieDetailMapper;
    @Autowired
    private BxjMediaFilesMapper bxjMediaFilesMapper;
    @Autowired
    private BxjUserMapper bxjUserMapper;
    @Autowired
    private BxjStarMapper bxjStarMapper;
    @Autowired
    private BxjMediaFileServiceImpl bxjMediaFileService;

    @Override
    public List<BxjMovieBaseVo> getCommentList() {
        LinkedList<BxjMovieBaseVo> bxjMovieBaseVos = new LinkedList<>();
        LambdaQueryWrapper<BxjMediaFiles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BxjMediaFiles::getFileType, FileType.BXJ_MOVIE_PICTURE);
        Page<BxjMediaFiles> page = new Page<>(1,5);
        Page<BxjMediaFiles> bxjMediaFilesPage = bxjMediaFilesMapper.selectPage(page, queryWrapper);
        List<BxjMediaFiles> bxjMediaFiles = bxjMediaFilesMapper.selectPage(page, queryWrapper).getRecords();
       for(BxjMediaFiles bxjMediaFile : bxjMediaFiles){
           BxjUser bxjUser = bxjUserMapper.selectById(bxjMediaFile.getUserId());
           BxjMovieBaseVo movieBaseDto = new BxjMovieBaseVo(
                   bxjMediaFile.getUrl(),
                   bxjMediaFilesMapper.selectOne(new LambdaQueryWrapper<BxjMediaFiles>()
                                   .eq(BxjMediaFiles::getId,bxjUser.getIcon()))
                           .getUrl(),
                   bxjUser.getUsername(), bxjMediaFile.getCreateDate().toString(),
                   bxjMovieMapper.selectOne(new LambdaQueryWrapper<BxjMovie>()
                           .eq(BxjMovie::getImgId, bxjMediaFile.getId())
                   ).getName()
           );
           bxjMovieBaseVos.add(movieBaseDto);
       }
        return bxjMovieBaseVos;
    }

    @Override
    public PageResult<BxjMovieDto> getPage(Map<String,Object> map) {
        PageResult<BxjMovieDto> listPageResult = new PageResult<>();
        // 获取分页参数
        int currentPage = (Integer) map.get("currentPage");
        int pageSize = (Integer) map.get("pageSize");
        Page<BxjMovie> page = new Page<>(currentPage, pageSize);

        LambdaQueryWrapper<BxjMovie> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(map.get("treeId").toString()),BxjMovie::getQuarterId, map.get("treeId"));
        queryWrapper.like(StringUtils.isNotEmpty(map.get("name").toString()),BxjMovie::getName, map.get("name"));
        queryWrapper.eq(StringUtils.isNotEmpty(map.get("status").toString()),BxjMovie::getStatus, map.get("status"));

        if(StringUtils.isNotEmpty(map.get("object").toString())){
            //根据传递的演员名在明星列表里查出id
            List<BxjStar> bxjStars = bxjStarMapper.selectList(new LambdaQueryWrapper<BxjStar>()
                    .like(BxjStar::getName, map.get("object")));
            List<String> bxjStarIds = bxjStars.stream()
                    .map(BxjStar::getId)  // 假设 BxjStar 类有 getId() 方法
                    .collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(bxjStars)){
                queryWrapper.in(BxjMovie::getObject,bxjStarIds);
            }
        }
        Page<BxjMovie> bxjMoviePage = bxjMovieMapper.selectPage(page,queryWrapper);
        List<BxjMovie> records = bxjMoviePage.getRecords();
        List<BxjMovieDto> bxjMovieBaseVos = records.stream()
                .map(bxjMovie -> {
                    BxjMovieDto bxjMovieDto = new BxjMovieDto();
                    BeanUtils.copyProperties(bxjMovie, bxjMovieDto);


                    // 获取与当前电影相关的详情信息
                    BxjMovieDetail bxjMovieDetail = bxjMovieDetailMapper
                            .selectOne(new LambdaQueryWrapper<BxjMovieDetail>()
                                    .eq(BxjMovieDetail::getMovieId, bxjMovie.getId()));
                    if (Objects.nonNull(bxjMovieDetail)) {
                        bxjMovieDto.setMediaFileId(bxjMovieDetail.getMediaFileId());
                        bxjMovieDto.setVideoUrl(bxjMediaFileService.getUrlById(false,bxjMovieDetail.getMediaFileId()));
                        bxjMovieDto.setDesc(bxjMovieDetail.getDecription());
                        bxjMovieDto.setCover(bxjMediaFileService.getUrlById(true,bxjMovie.getImgId()));
                    }

                    return bxjMovieDto;
                })
                .collect(Collectors.toList());  // 收集为一个新的 List

        listPageResult.setTotal(bxjMoviePage.getTotal());
        listPageResult.setPageSize(pageSize);
        listPageResult.setCurrentPage(currentPage);
        listPageResult.setList(bxjMovieBaseVos);
        return listPageResult;
    }

    @Resource
    IdUtil idUtil;
    
    @Override
    @Transactional
    public boolean change(Map<String, Object> map) {
        ArrayList<String> quarters = (ArrayList<String>) map.get("quarter");
        String join = String.join(", ", quarters);

        // 判断电影是否存在
        if (Objects.nonNull(map.get("id"))) {
            BxjMovie oldMovie = bxjMovieMapper.selectById(map.get("id").toString());
            updateMovie(oldMovie, map, join);
            BxjMovieDetail bxjMovieDetail = getMovieDetail(oldMovie.getId());
            updateMovieDetail(bxjMovieDetail, map);
            return bxjMovieDetailMapper.updateById(bxjMovieDetail) > 0;
        }

        // 如果电影不存在，创建新的电影和详情
        BxjMovie bxjMovie = createNewMovie(map, join);
        BxjMovieDetail bxjMovieDetail = createNewMovieDetail(bxjMovie.getId(), map);

        bxjMovieMapper.insert(bxjMovie);  // 保存电影
        return bxjMovieDetailMapper.insert(bxjMovieDetail) > 0;  // 保存电影详情
    }

    @Override
    public boolean updateStatus(String id, Integer status) {
        BxjMovie bxjMovie = bxjMovieMapper.selectById(id);
        // 如果找不到对应的明星记录，返回 false
        if (bxjMovie == null) {
            return false;
        }
        // 设置新的状态
        bxjMovie.setStatus(status);
        // 如果更新影响的行数大于 0，表示更新成功
        return  bxjMovieMapper.updateById(bxjMovie)>0;
    }

    @Override
    @Transactional
    public boolean deleteMovie(BxjMovieDto bxjMovieDto) {
        bxjMovieMapper.deleteById(bxjMovieDto.getId());
        return bxjMovieDetailMapper
                .delete(new LambdaQueryWrapper<BxjMovieDetail>()
                        .eq(BxjMovieDetail::getMovieId,bxjMovieDto.getId()))>0;
    }

    @Override
    @Transactional
    public boolean deleteBatch(String[] ids) {
        bxjMovieMapper.deleteBatchIds(Arrays.asList(ids));
        List<String> movieIds = Arrays.stream(ids)
                .map(id -> bxjMovieDetailMapper.selectOne(new LambdaQueryWrapper<BxjMovieDetail>().eq(BxjMovieDetail::getMovieId, id)))
                .filter(Objects::nonNull)
                .map(BxjMovieDetail::getMovieId) // 提取 starId
                .collect(Collectors.toList());
        // 批量删除 BxjStarDetail
        if (!movieIds.isEmpty()) {
            bxjMovieDetailMapper.delete(new LambdaQueryWrapper<BxjMovieDetail>().in(BxjMovieDetail::getMovieId, movieIds));
        }
        return true;
    }

    // 更新现有电影信息
    private void updateMovie(BxjMovie movie, Map<String, Object> map, String join) {
        movie.setName(map.get("name").toString());
        movie.setObject(map.get("object").toString());
        if (ObjectUtils.isNotEmpty(map.get("imgMd5"))) movie.setImgId(map.get("imgMd5").toString());
        movie.setQuarterId(join);
        if (ObjectUtils.isNotEmpty(map.get("status"))) {
            movie.setStatus(Integer.parseInt(map.get("status").toString()));
        }
        movie.setUserId("1");
        movie.setVc("0");
        movie.setLiked("0");
        bxjMovieMapper.updateById(movie);
    }

    // 获取电影详情
    private BxjMovieDetail getMovieDetail(String movieId) {
        LambdaQueryWrapper<BxjMovieDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BxjMovieDetail::getMovieId, movieId);
        return bxjMovieDetailMapper.selectOne(queryWrapper);
    }

    // 更新电影详情
    private void updateMovieDetail(BxjMovieDetail movieDetail, Map<String, Object> map) {
        movieDetail.setDecription(map.get("desc").toString());
        if (ObjectUtils.isNotEmpty(map.get("videoMd5"))) {
            movieDetail.setMediaFileId(map.get("videoMd5").toString());
        }
    }

    // 创建新的电影
    private BxjMovie createNewMovie(Map<String, Object> map, String join) {
        BxjMovie movie = new BxjMovie();
        movie.setId(String.valueOf(idUtil.nextId(BxjType.BXJ_MOVIE)));
        movie.setName(map.get("name").toString());
        movie.setObject(map.get("object").toString());
        if (ObjectUtils.isNotEmpty(map.get("imgMd5"))) movie.setImgId(map.get("imgMd5").toString());
        movie.setQuarterId(join);
        if (ObjectUtils.isNotEmpty(map.get("status"))) {
            movie.setStatus(Integer.parseInt(map.get("status").toString()));
        }
        movie.setUserId("1");
        movie.setVc("0");
        movie.setLiked("0");
        return movie;
    }

    // 创建新的电影详情
    private BxjMovieDetail createNewMovieDetail(String movieId, Map<String, Object> map) {
        BxjMovieDetail movieDetail = new BxjMovieDetail();
        movieDetail.setId(String.valueOf(idUtil.nextId(BxjType.BXJ_MOVIE_DETAIL)));
        movieDetail.setMovieId(movieId);
        movieDetail.setDecription(map.get("desc").toString());
        if (ObjectUtils.isNotEmpty(map.get("videoMd5"))) {
            movieDetail.setMediaFileId(map.get("videoMd5").toString());
        }
        return movieDetail;
    }
}
